package com.kuangjia.student_ems.controller;

import com.kuangjia.student_ems.dto.JwtAuthResponseDTO;
import com.kuangjia.student_ems.dto.LoginDTO;
import com.kuangjia.student_ems.dto.UserDTO;
import com.kuangjia.student_ems.dto.request.UserCreateRequest;
import com.kuangjia.student_ems.security.JwtTokenProvider;
import com.kuangjia.student_ems.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenProvider tokenProvider;

    @PostMapping("/login")
    public ResponseEntity<JwtAuthResponseDTO> authenticateUser(@Valid @RequestBody LoginDTO loginDto) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 获取token
        String token = tokenProvider.generateToken(authentication);
        
        // 获取用户信息
        UserDTO user = userService.getUserByUsername(loginDto.getUsername());

        return ResponseEntity.ok(new JwtAuthResponseDTO(token, user.getId(), user.getUsername(), 
                user.getName(), user.getRole().toString()));
    }

    @PostMapping("/register")
    public ResponseEntity<UserDTO> registerUser(@Valid @RequestBody UserCreateRequest registerDto) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(registerDto.getUsername())) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        // 创建用户
        UserDTO createdUser = userService.createUser(registerDto);
        return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
    }
} 